<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/1/8
 * Time: 下午3:33
 */

namespace Biz\service;

use Biz\cache\Goods as cGoods;
use Biz\cache\GoodsBasicInfo;
use Biz\cache\GoodsBasicInfo as cGoodsBaseInfo;
use Biz\cache\GoodsExtendInfo;
use Biz\cache\GoodsExtendInfo as cGoodsExtendInfo;
use Biz\cache\GoodsSkuId;
use Biz\cache\ShopRecommendSpecial as cShopRecommendSpecial;
use Biz\cache\ShopSpecial as cShopSpecial;
use Biz\cache\Sku;
use Biz\cache\SkuBase as cSkuBase;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\GoodsExtendInfo as mGoodsExtendInfo;
use Biz\model\GoodsPriceLog;
use Biz\model\GoodsSku as mGoodsSku;
use Biz\model\ShippingTempl as mShippingTempl;
use Biz\model\ShopSpecialGoods as mShopSpecialGoods;
use Biz\model\trade\Cart as mCart;
use Biz\model\trade\CartV as mCartV;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\wiki\SpuRelateWiki;
use Biz\module\Classes\adm\GoodsSearch as clsAdmGoodsSearch;
use Biz\module\Classes\GoodsStatus as clsGoodsStatus;
use Biz\module\Classes\mgt\GoodsSave as clsMgtGoodsSave;
use Biz\pockets\constInterface\CategoryExtendInfo;
use Biz\pockets\excel\DownExcel;
use Biz\pockets\serviceTrait\_Async;
use Biz\service\activity\ActivityRegisterInfo;
use Biz\service\activity\FlashSale;
use Biz\service\activity\NewComer;
use Biz\service\activity\PinTuan as sPinTuan;
use Biz\service\search\Goods as searchGoods;
use Biz\service\ShopMall as sShopMall;
use Biz\service\Sku as sSku;
use Biz\tools\Mail;
use Doraemon\model\admTag;
use Biz\model\brand\Brand as mBrand;
use Doraemon\model\Category as mCategory;
use Doraemon\model\SkuAttributes as mSkuAttributes;
use Doraemon\model\Spu as mSpu;
use Biz\service\brand\Brand;
use Doraemon\service\Search;
use Doraemon\service\Search as sSearch;
use Doraemon\service\Spu;
use Doraemon\service\User;
use Doraemon\tools\ImgUrl as toolImgUrl;
use Doraemon\tools\Log as tLog;
/**
 * @deprecated
 */
class GoodsInfo implements CategoryExtendInfo
{
    use _Async;

    public static function searchWiki($uid, $keyword, $page, $pagesize = 20)
    {
        $page = abs($page);

        //获取支持的分类
        $categories = ShopCommissionRate::getCategoryRate($uid);

        $supportCates = array_shift($categories);
        $categoryIds = [];

        foreach ($supportCates as $value) {
            foreach ($value['children'] as $val) {
                $categoryIds[] = $val['cate_id'];
            }
        }

        if (empty($categoryIds)) {
            throw new \Exception('请先设置佣金比例');
        }
        $keywords = sSearch::_getScwsTag($keyword);

        $list['total'] = 0;

        if ($keywords) {
            $brandstr = implode(" AND admin_tag:", $keywords);

            $list = sSearch::searchByField('search_mod', 'product', [
                'category_ids' => $categoryIds,
                'admin_tag' => $brandstr,
                'status' => mSpu::STATUS_REVIEW,
                'sort' => ['is_cover_img'],
                'page' => $page,
                'pagesize' => $pagesize
            ]);
        }


        if ($list['total']) {

            $idList = array_column($list['rows'], 'id');
            $list['rows'] = mSpu::getSpuByIds($idList, [
                'id',
                'title',
                'category_id(second_category_id)',
                'third_category_id',
                'cover_img(img_url)',
                'brand_id'
            ]);

            $brandIds = array_column($list['rows'], 'brand_id');
//            $categoryIds = array_column($list['rows'], 'third_category_id');
//
//            $cates = mCategory::selectCategorys($categoryIds);
            $brands = mBrand::getBrandListByIds($brandIds);

            array_walk($list['rows'], function (&$v) use ($brands) {
                $v['img_url'] = toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $v['img_url'],
                    toolImgUrl::IMAGE_SIZE_O_500);
                $v['cate_name'] = mCategory::getStrTreeById($v['third_category_id'] ? $v['third_category_id'] : $v['second_category_id']);
                if (isset($v['brand_id'])) {
                    $v['brand_name'] = $brands[$v['brand_id']]['brand_name'];
                }
                unset($v['third_category_id']);
            });

            return [
                'page' => [
                    'prevPage' => $page - 1 > 0 ? $page - 1 : null,
                    'nextPage' => $page + 1 <= ceil($list['total'] / $pagesize) ? $page + 1 : null,
                    'totalPage' => ceil($list['total'] / $pagesize),
                ],
                'list' => $list['rows']
            ];
        } else {
            return [
                'page' => [],
                'list' => []
            ];
        }


    }

    public static function mgtGetGoodsInfo($uid, $goodsId)
    {

        //查询商品基础信息
        $info = mGoodsBasicInfo::getInfo($goodsId, [
            'uid',
            'shop_id',
            'goods_id',
            'brand_id',
            'title',
            'category_id',
            'second_category_id',
            'third_category_id',
            'four_category_id',
            'status'
        ]);

        if (empty($info) || $info['uid'] != $uid) {
            throw new \Exception('商品不存在，或越权操作');
        }

        $info['categorynav'] = mCategory::getStrTree([
            $info['category_id'],
            $info['second_category_id'],
            $info['third_category_id'],
            $info['four_category_id']
        ]);

        $info['category_list'] = [];
        $categories = mCategory::selectCategorys([
            $info['category_id'],
            $info['second_category_id'],
            $info['third_category_id'],
            $info['four_category_id']
        ]);
        foreach (['category_id', 'second_category_id', 'third_category_id', 'four_category_id'] as $categoryItem) {
            if (isset($info[$categoryItem]) && $info[$categoryItem]) {
                $info['category_list'][] = [
                    'cate_id' => $categories[$info[$categoryItem]]['cate_id'],
                    'cate_name' => $categories[$info[$categoryItem]]['cate_name']
                ];
            }
        }


        if ($info['four_category_id']) {
            $info['category_id'] = $info['four_category_id'];
        } elseif ($info['third_category_id']) {
            $info['category_id'] = $info['third_category_id'];
        } elseif ($info['second_category_id']) {
            $info['category_id'] = $info['second_category_id'];
        }

        //查询品牌信息
        $brand = mBrand::getInfo($info['brand_id']);

        $info['brand_name'] = $brand['brand_name'];

        //查询商品sku信息
        $skuInfo = mGoodsSku::getSkuInfo([$goodsId], true, false);

        $info['sku'] = array_shift($skuInfo);

        //查询商品的扩展信息
        $extendInfo = mGoodsExtendInfo::getInfo($goodsId);

        $info = array_merge($info, $extendInfo);


        $shippingTempl = mShippingTempl::getTemplById($info['shop_id'], $extendInfo['shipping_templ_id']);

        $info['shipping_templ'] = $shippingTempl;

        $registerInfos = ActivityRegisterInfo::getRegisterInfos([$goodsId]);
        $registerSpecialInfos = ShopSpecial::getRegisterSpecialInfos([$goodsId]);

        $flashTags = FlashSale::mgtFlashSaleTags([$goodsId]);
        $newComerTags = NewComer::mgtNewcommerTags([$goodsId]);

        $info['register_tags'] = isset($registerInfos[$goodsId]) ? array_column($registerInfos[$goodsId], 'title') : [];
        $info['activity_register_tags'] = isset($registerSpecialInfos[$goodsId]) ? array_column($registerSpecialInfos[$goodsId], 'special_title') : [];
        $info['flashsale_tags'] = isset($flashTags[$goodsId]) ? $flashTags[$goodsId] : [];
        $info['newcommer_exclusive_tags'] = isset($newComerTags[$goodsId]) ? $newComerTags[$goodsId] : [];

        $info['shipping_templ'] = $shippingTempl;

        $info = self::extendInfoBaseCateId($info);

        if ($info['shipping_time_type'] == mGoodsExtendInfo::SHIPPING_TIME_TYPE_SPOT) {
            if ($info['shipping_time'] > 72 && in_array($info['shipping_time'],[96,120,144])) {
                $info['shipping_time'] = $info['shipping_time'] / 24;
            }
        }

        return $info;
    }

    private static function extendInfoBaseCateId($info)
    {
        //家具类商品
        if ($info['category_list'][0]['cate_id'] == self::CATEGORY_ID_FURNITURE) {
            $info['mounting_methods'] = [];
            foreach (self::CATEGORY_FURNITURE_MOUNT_METION as $methodId => $method) {
                $info['mounting_methods'][] = [
                    'id' => $methodId,
                    'item' => $method,
                    'is_selected' => $methodId == $info['mounting_method'] ? 1 : 0
                ];
            }
        }
        return $info;
    }

    public static function admGetGoodsInfo($goodsId)
    {

        //查询商品基础信息
        $info = mGoodsBasicInfo::getInfo($goodsId, "*");

        //查询品牌信息
        $brand = mBrand::getInfo($info['brand_id']);

        $info['brand_name'] = $brand['brand_name'];


        return $info;
    }

    /**
     * 返回属于店铺的商品id
     * @param $goods_ids
     * @param $shopId
     * @param $status
     * @return array
     */
    public static function checkDownLoadGoods($goods_ids, $shopId, $status)
    {
        $rs = mGoodsBasicInfo::select('goods_id', $where = [
            'goods_id' => $goods_ids,
            'shop_id' => $shopId,
            'status' => $status
        ]);
//var_dump(mGoodsBasicInfo::log());
        return $rs;
    }

    public static function downLoadAllGoods($shopId)
    {
        $size = 500;
        $response = [];
        if ($shopId > 0) {
            $where = [
                'status[!]' => [
                    mGoodsBasicInfo::STATUS_DELETE
                ],
                'shop_id' => $shopId
            ];
            $count = mGoodsBasicInfo::getGoodsCount($where);
            $totalPage = ceil($count / $size);
            for ($i = 1; $i <= $totalPage; $i++) {
                $list = mGoodsBasicInfo::getAllGoods($where, [($i - 1) * $size, $size], ['goods_id' => 'DESC']);
                if ($list) {
                    foreach ($list as $v) {
                        $response[] = [
                            'goods_id' => $v['goods_id'],
                            'title' => $v['title'],
                            'price' => bcsub($v['max_price'], $v['min_price'], 2) == 0 ? $v['min_price'] : $v['min_price'] . '~' . $v['max_price'],
                            'platform' => '',
                            'shop_id' => '',
                            'shop_name' => '',
                            'shop_spu' => '',
                            'brand_name' => '',
                        ];
                    }
                }
            }
        }
        return $response;
    }

    /**
     * 查询商品
     *
     * @param     $status
     * @param     $shopId
     * @param     $goodsId
     * @param     $title
     * @param     $startTime
     * @param     $endTime
     * @param     $sort
     * @param int $page
     * @param int $pageSize
     * @param $isAdminOffline mixed 是否管理员下架
     *
     * @return array
     */
    public static function searchGoods(
        $status,
        $shopId,
        $goodsId,
        $title,
        $startTime,
        $endTime,
        $sort,
        $page = 1,
        $pageSize = 20,
        $isAdminOffline = null
    )
    {
        $where = [];
        $limit = [($page - 1) * $pageSize, $pageSize];
        $sort = $sort ? array_merge($sort, ['goods_id' => 'DESC']) : [];
        if ($shopId) {
            $where['shop_id'] = $shopId;
        }
        if ($status) {
            $where['status'] = $status;
        }
        if ($goodsId) {
            $where['goods_id'] = $goodsId;
        }
        if ($title) {
            $where['title[~]'] = $title;
        }
        if ($startTime && $endTime) {
            $where['operate_time[>=]'] = $startTime;
            $where['operate_time[<=]'] = $endTime;
        }
        if (!is_null($isAdminOffline)) {
            if ($isAdminOffline) {
                $where['operate_adminuid[>]'] = 0;
            } else {
                $where['operate_adminuid'] = 0;
            }
        }
        $list = mGoodsBasicInfo::getGoods($where, $limit, $sort);
        $count = mGoodsBasicInfo::getGoodsCount($where);
        $goodsIds = array_column($list, 'goods_id');
        $extendInfo = mGoodsExtendInfo::getRemarksAndShippingTempl($goodsIds);
        $skuInfo = mGoodsSku::getSkuInfo($goodsIds, true, false);
        $selectedInfos = ShopSpecial::getRegisterSpecialInfos(array_column($list, 'goods_id')); // 选中的周末购
        $registerInfos = ActivityRegisterInfo::getRegisterInfos($goodsIds); // 参加的报名
        $flashTags = FlashSale::mgtFlashSaleTags($goodsIds); // 参加的限时抢
        $newComerTags = NewComer::mgtNewcommerTags($goodsIds); // 参加的新人价
        $pinTuanTags = sPinTuan::getPintuanList($goodsIds); // 参与的拼团
        $wikiMap = SpuRelateWiki::checkExists($goodsIds); //是否转换wiki

        foreach ($list as &$row) {
            $row['remark'] = isset($extendInfo[$row['goods_id']]['remark']) ? $extendInfo[$row['goods_id']]['remark'] : '';
            $row['activity_register_tags'] = isset($selectedInfos[$row['goods_id']]) ? array_column($selectedInfos[$row['goods_id']], 'special_title') : [];
            $row['register_tags'] = isset($registerInfos[$row['goods_id']]) ? array_column($registerInfos[$row['goods_id']], 'title') : [];
            $row['sku'] = isset($skuInfo[$row['goods_id']]) ? $skuInfo[$row['goods_id']] : [];
            $row['flashsale_tags'] = isset($flashTags[$row['goods_id']]) ? $flashTags[$row['goods_id']] : [];
            $row['newcommer_exclusive_tags'] = isset($newComerTags[$row['goods_id']]) ? $newComerTags[$row['goods_id']] : [];
            $row['pintuan_tags'] = !empty($pinTuanTags[$row['goods_id']]) ?
                '拼团 ' . date('m/d', $pinTuanTags[$row['goods_id']]['time_down']['begin_time']) . ' 至 ' . date('m/d', $pinTuanTags[$row['goods_id']]['time_down']['end_time']) : '';
            $row['wiki'] = in_array($row['goods_id'], $wikiMap);
        }
        return ['list' => $list, 'count' => $count];
    }

    public static function getCountByStatus($shopId, $status)
    {
        $result = [];
        if (!is_array($status)) {
            $status = array($status);
        }
        foreach ($status as $row) {
            $result[$row] = mGoodsBasicInfo::getGoodsCount(['shop_id' => $shopId, 'status' => $row]);
        }
        return $result;
    }

    public static function mgtSaveShippingTime($shopId, array $goodsIds, $shippingType, $shippingTime)
    {
        try {

            $res = mGoodsExtendInfo::action(function () use ($shopId, $goodsIds, $shippingType, $shippingTime) {
                $goodsBasicInfos = mGoodsBasicInfo::getInfos(['goods_id' => $goodsIds, 'shop_id' => $shopId]);
                $goodsIds = array_column($goodsBasicInfos, 'goods_id');
                if (!$goodsIds) throw new \Exception('请选择商品');

                $cls = new clsMgtGoodsSave();
                $res = $cls->saveShippingTime($goodsIds, $shippingType, $shippingTime);
                return $res;
            });

            GoodsExtendInfo::mDelItems($goodsIds);

            tLog::goods_saveShipping_debug('商家修改shippingtime', [
                'shop_id' => $shopId,
                'goods_id' => $goodsIds,
                'data' => [$shippingType, $shippingTime],
            ]);

        } catch (\Exception $e) {
            tLog::error('商家保存发货时间信息出现异常', [
                'uid' => $shopId,
                'goods_id' => $goodsIds,
                'data' => [$shippingType, $shippingTime],
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);
            throw $e;

        }
    }

    public static function mgtSaveSku($shopId, $goodsId, $skuInfo)
    {
        try {

            $res = mGoodsBasicInfo::action(function () use ($shopId, $goodsId, $skuInfo) {
                $cls = new clsMgtGoodsSave();
                $res = $cls->saveSku($shopId, $goodsId, $skuInfo);
                self::updateBasicGoodsInfo($shopId, $goodsId);
                return $res;
            });


            if ($res !== false) {
                //设置库存缓存
                Stock::setStockCache($goodsId);
                //删除goodsskuid关系缓存
                GoodsSkuId::delCache($goodsId);
                //根据goods_id 删除 skuinfo 缓存
                Sku::delCache([], $goodsId);
                //更新商品solr
                searchGoods::updateByGoodsId($goodsId);
                cSkuBase::delItem($goodsId);
                tLog::goods_saveSku_debug('商家修改sku库存价格', [
                    'shop_id' => $shopId,
                    'goods_id' => $res['goods_id'],
                    'goods_detail' => $skuInfo
                ]);
            }

        } catch (\Exception $e) {
            tLog::error('商家保存sku信息出现异常', [
                'uid' => $shopId,
                'goods_id' => $goodsId,
                'data' => $skuInfo,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }

    private static function updateBasicGoodsInfo($shopId, $goodsId)
    {
        $skuInfos = mGoodsSku::select_master('*', [
            'goods_id' => $goodsId,
            'shop_id' => $shopId,
            'status' => mGoodsSku::STATUS_PASSED
        ]);
        return mGoodsBasicInfo::updateData([
            'min_price' => min(array_column($skuInfos, 'price')),
            'max_price' => max(array_column($skuInfos, 'price')),
            'stock' => array_sum(array_column($skuInfos, 'stock')),
        ], [
            'goods_id' => $goodsId
        ]);
    }


    /*
     * @param $uid
     * @param $goodsId
     * @param $data
     *
     * 商家创建或编辑商品
     */
    public static function mgtSaveGoods($uid, $goodsId, $post)
    {

        try {
            $res = mGoodsBasicInfo::action(function () use ($goodsId, $post) {
                $cls = new clsMgtGoodsSave();
                if ($goodsId > 0) {
                    $res = $cls->update($post);
                } else {
                    $res = $cls->create($post);
                }
                return $res;
            });

            if ($res !== false) {

                //如果状态为上架则进行状态修改操作
                if (!empty($post['btn_id'])) {
                    switch ($post['btn_id']) {
                        case clsMgtGoodsSave::BTN_ID_SAVE_STATUS_ONLINE:
                            clsGoodsStatus::mgtOnline($uid, $uid, $res['goods_id']);
                            break;
                        case clsMgtGoodsSave::BTN_ID_SAVE_STATUS_WAIT_AUDIT:
                            clsGoodsStatus::mgtDelivered($uid, $uid, $res['goods_id']);
                            break;

                    }

                } else {
                    //创建商品的时候，默认是下架状态
                    if ($goodsId == 0) {
                        clsGoodsStatus::mgtOffline($uid, $uid, $res['goods_id']);
                    }
                }


                //设置库存缓存
                Stock::setStockCache($res['goods_id']);
                //删除商品缓存
                cGoods::delGoods($res['goods_id']);
                cGoodsBaseInfo::delItem($res['goods_id']);
                cGoodsExtendInfo::delItem($res['goods_id']);
                //删除goodsskuid关系缓存
                GoodsSkuId::delCache($res['goods_id']);
                //根据goods_id 删除 skuinfo 缓存
                Sku::delCache([], $res['goods_id']);
                //更新商品solr
                searchGoods::updateByGoodsId($res['goods_id']);
                //删除专题缓存
                cShopRecommendSpecial::delSpecial(sShopMall::SPECIAL_CHCHE_NAME);
                $specialId = mShopSpecialGoods::getSpecialIdsByGid($goodsId);
                $specialId = array_unique($specialId);
                array_map(function ($v) {
                    cShopSpecial::delSpecial($v);
                }, $specialId);

                searchGoods::updateByGoodsId($res['goods_id']);

                tLog::goods_saveGoods_debug('商家保存商品', [
                    'shop_id' => $uid,
                    'goods_id' => $res['goods_id'],
                    'goods_detail' => $post
                ]);
            }

        } catch (\Exception $e) {
            tLog::error('商家保存商品出现异常', [
                'uid' => $uid,
                'goods_id' => $goodsId,
                'data' => $post,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }

    /**
     * 自建商品创建或则同步wiki
     *
     * @param $goodsInfo 商品信息
     */
    public static function createOrSyncWiki($goodsInfo)
    {
        return self::_async($goodsInfo);
    }

    public static function _async_createOrSyncWiki($goodsInfo)
    {
        try {
            $wikiData = [];
            if ($goodsInfo) {
                $wikiId = 0;
                if (isset($goodsInfo['wiki_id']) && $goodsInfo['wiki_id']) {
                    self::syncWikiTag($goodsInfo['wiki_id'], $goodsInfo['style_content']);
                    $wikiId = $goodsInfo['wiki_id'];
                } else {
                    $wikiData['wiki_type'] = mSpu::WIKI_TYPE_SHOP;
                    $wikiData['title'] = $goodsInfo['title'];
                    $wikiData['brand_id'] = $goodsInfo['brand_id'];
                    $wikiData['category_id'] = $goodsInfo['category_id'];
                    $wikiData['last_category_id'] = $goodsInfo['last_category_id'];
                    $wikiData['cover_img'] = $goodsInfo['spec_img'];
                    $wikiData['imgs'] = $goodsInfo['images_content'];
                    $wikiData['min_price'] = $goodsInfo['min_price'];
                    $wikiData['max_price'] = $goodsInfo['max_price'];
                    $wikiData['create_time'] = date('Y-m-d H:i:s');
                    $wikiData['edit_time'] = date('Y-m-d H:i:s');
                    $wikiData['status'] = mSpu::STATUS_REVIEW;
                    //风格 tags
                    $styleContent = $goodsInfo['style_content'];
                    if (explode(',', $styleContent) !== false) {
                        $tagIds = explode(',', $styleContent);
                        $tagArr = admTag::getTagByIds($tagIds, ['tag']);
                        $tagList = array_column($tagArr, 'tag');
                        if ($tagList) {
                            $wikiData['tags'] = implode(',', $tagList);
                        }
                    }
                    $wikiId = mSpu::insertSpu($wikiData);
                    if ($wikiId) {
                        //更改商品wikiid
                        mGoodsBasicInfo::updateData(['wiki_id' => $wikiId], ['goods_id' => $goodsInfo['goods_id']]);
                        cGoods::delGoods($goodsInfo['goods_id']);
                        GoodsBasicInfo::delItem($goodsInfo['goods_id']);
                        //同步材质和尺寸
                        $material = [];
                        $size = [];

                        if ($goodsInfo['material_content']) {//材质
                            $materialArr = [];
                            foreach ($goodsInfo['material_content'] as $row) {
                                $materialArr[] = ['key' => $row['title'], 'value' => $row['content']];
                            }
                            $material = [
                                "spu_id" => $wikiId,
                                "dimension" => mSkuAttributes::TYPE_MATERIAL,
                                "detail" => json_encode($materialArr, JSON_UNESCAPED_UNICODE),
                                "status" => mSkuAttributes::STATUS_NORMAL
                            ];
                        }
                        if ($goodsInfo['extinfo'] && $goodsInfo['extinfo'][0] != '[]' && $goodsInfo['extinfo'][0] != 'null') {//尺寸
                            $size = [
                                "spu_id" => $wikiId,
                                "dimension" => mSkuAttributes::TYPE_SIZE,
                                "detail" => json_encode($goodsInfo['extinfo'], JSON_UNESCAPED_UNICODE),
                                "status" => mSkuAttributes::STATUS_NORMAL
                            ];
                        }
                        mSkuAttributes::addSkuInfos($wikiId, [array_merge($material, $size)]);
                    } else {
                        tLog::error('商家保存商品新建wiki异常', [
                            'wiki_data' => $wikiData,
                        ]);
                    }
                }
                Search::updateProductById($wikiId);
            }
        } catch (\Exception $e) {
            tLog::error('商家保存商品同步wiki异常', [
                'goods_info' => $goodsInfo,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }

    /**
     * 同步商品风格到商品wiki标签(按wiki模板创建商品)
     *
     * @param $wikiId
     * @param $styleContent
     *
     * @return bool
     */
    private static function syncWikiTag($wikiId, $styleContent)
    {
        if (explode(',', $styleContent) !== false) {
            $tagIds = explode(',', $styleContent);
            $tagArr = admTag::getTagByIds($tagIds, ['tag']);
            $tagList = array_column($tagArr, 'tag');
            if ($tagList) {
                $wikiTag = [];
                $spuInfo = Spu::getSpuById($wikiId);
                if ($spuInfo) {
                    $tag = $spuInfo['tags'];
                    $tag = trim($tag, ',');
                    if ($tag) {
                        $wikiTag = explode(',', $tag);
                    }
                }
                $tagList = array_merge($wikiTag, $tagList);
                $tagList = array_unique($tagList);
                $tagStr = implode(',', $tagList);
                return mSpu::updateSpuTags($wikiId, $tagStr);
            }
        }
        return false;
    }


    public static function admSearchGoodsList($params, $limit)
    {

        $params['sort'] = self::admSortType($params['status']);
        $search = new clsAdmGoodsSearch($params, $limit);

        return [
            'list' => $search->getList(),
            'total' => $search->getCount(),
        ];

    }

    private static function admSortType($status)
    {
        $sortTypeMap = [
            'online' => ['id' => 'DESC'],
            'offline' => ['operate_time' => 'DESC'],
            'waitaudit' => ['operate_time' => 'DESC'],
        ];

        return $sortTypeMap[$status];
    }


    public static function admDownLoadResults($params, $adminEmail)
    {
        $fields = [
            'id' => '商品ID',
            'title' => '商品名称',
            'shop_id' => '商家ID',
            'shop_name' => '商家名称',
            'brand_id' => '品牌ID',
            'brand_name' => '品牌名称',
            'category_name' => '一级分类',
            'second_category_name' => '二级分类',
            'third_category_name' => '三级分类',
            'four_category_name' => '四级分类',
            'sku_id' => 'SKU id',
            'sku_name' => 'SKU 名称',
            'price' => '售价',
            'sku_stock' => '库存',
            'sku_add_cart_num' => '累计加购数量',
            'sku_add_cart_people_num' => '累计加购人数',
            'sku_sell_num' => '累计销量',
            'first_online_time' => '首次上架时间',
            'tags_content' => '标签',
            'heat_tag' => '商品标签',
        ];

        $params['sort'] = self::admSortType($params['status']);
        $search = new clsAdmGoodsSearch($params, []);

        $result = $search->download($fields);
        if (!$result['rows']) {
            return [];
        }

        $shopIds = array_column($result['rows'], 'shop_id');
        $brandIds = array_column($result['rows'], 'brand_id');
        $shopInfos = User::getUsers($shopIds);
        $brandInfos = Brand::getBrandListByIds4App($brandIds);
        $goodsIds = array_column($result['rows'], 'id');
        $skuInfo = self::getSkuInfo($goodsIds);
        $goodsInfo = array_column($result['rows'], null, 'id');

        foreach ($skuInfo as $goodsId => $info) {
            foreach ($info as $row) {
                foreach ($fields as $field => $v) {
                    if ($field == 'brand_name') {
                        $values['brand_name'] = isset($brandInfos[$goodsInfo[$goodsId]['brand_id']]) ? $brandInfos[$goodsInfo[$goodsId]['brand_id']]['name'] : '';
                    } elseif ($field == 'shop_name') {
                        $values['shop_name'] = isset($shopInfos[$goodsInfo[$goodsId]['shop_id']]) ? $shopInfos[$goodsInfo[$goodsId]['shop_id']]['nick'] : '';
                    } else {
                        if (isset($goodsInfo[$goodsId][$field])) {
                            $values[$field] = isset($goodsInfo[$goodsId][$field]) ? $goodsInfo[$goodsId][$field] : '';
                        } else {
                            $values[$field] = isset($row[$field]) ? $row[$field] : '';
                        }
                    }
                }
                $list[] = $values;
            }
        }
        if ($list) {
            $header = ['商品ID', '商品名称', '商家ID', '商家名称', '品牌ID', '品牌名称', '一级分类', '二级分类', '三级分类', '四级分类', 'SKU id', 'SKU 名称', '售价', '库存', '累计加购数量', '累计加购人数', '累计销量', '首次上架时间', '标签', '商品标签'];

            $letter = range('A', 'T');

            $excelObj = new DownExcel();
            $excelObj->saveType = 1;
            $excelObj->setFileName('商品列表导出');
            $excelObj->setSheetTitle('商品列表导出');
            //设置列宽
            $widths = ['A' => 15, 'B' => 30, 'C' => 15, 'D' => 30, 'E' => 20, 'F' => 20, 'G' => 15, 'H' => 10, 'I' => 10, 'J' => 20, 'K' => 20, 'L' => 20, 'M' => 20, 'N' => 20, 'O' => 20, 'P' => 20, 'Q' => 20, 'R' => 20, 'S' => 20, 'T' => 20];
            $excelObj->setWidth($widths);
            //默认单元格居中
            $excelObj->setDefaultStyleAlignment();
            foreach ($header as $key => $value) {
                //设置字体
                $excelObj->setFrontName($letter[$key]);
                //设置大小
                $excelObj->setFrontSize($letter[$key]);
            }

            $fileName = $excelObj->create($list, $header);
            Mail::send($adminEmail, '商品列表导出商品' . date('Y-m-d H:i:s'), '商品列表导出商品' . date('Y-m-d H:i:s'), $fileName);
        }

        return true;
    }

    public static function admGetNeedAuditGoodsTotal()
    {
        $total = mGoodsBasicInfo::count('*', ['status' => mGoodsBasicInfo::STATUS_WAIT_AUDIT]);

        return $total;
    }

    public static function admChangeGoodsStatus($goodsId, $oldStatus, $action, $remark, $adminUid = 0)
    {

        try {
            $info = mGoodsBasicInfo::getInfo($goodsId);

            if ($info['status'] != $oldStatus) {
                throw new \Exception('提交失败');
            }

            clsGoodsStatus::checkAdminAction($oldStatus, $action);

            call_user_func_array('Biz\module\Classes\GoodsStatus::' . $action, [
                $goodsId,
                $adminUid,
                $remark,
            ]);

            //删除商品缓存
            cGoods::delGoods($goodsId);
            GoodsBasicInfo::delItem($goodsId);

            //删除sku信息
            Sku::delCache([], $goodsId);
            searchGoods::updateByGoodsId($goodsId);

            //删除专题缓存
            $specialId = mShopSpecialGoods::getSpecialIdsByGid($goodsId);
            $specialId = array_unique($specialId);
            array_map(function ($v) {
                cShopSpecial::delSpecial($v);
            }, $specialId);

        } catch (\Exception $e) {
            tLog::warning('管理员修改商品状态失败', [
                'goods_id' => $goodsId,
                'old_status' => $oldStatus,
                'action' => $action,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }

    /**
     * @param $goodsId
     * @param array $priceInfo
     * [
     *   [
     *      'sku_id' => 1,
     *      'sku_name' => 红色 xl,
     *      'price' => 4.00
     *   ]
     * ]
     * @param $log_type
     */
    public static function admAddPriceLog($goodsId, array $priceInfos, $log_type = GoodsPriceLog::LOG_TYPE_NORMAL)
    {
        $priceInfos = array_filter($priceInfos, function ($priceInfo) use ($goodsId, $log_type) {

            return GoodsPriceLog::is_can_add($goodsId, $priceInfo['sku_name'], $priceInfo['price'], $log_type);

        });

        return GoodsPriceLog::addLog($goodsId, $priceInfos, $log_type);


    }

    public static function updateProductSolrByGid($goods_id)
    {
        $wikiid = GoodsDetail::formatBasicInfos([$goods_id])[$goods_id]['wiki_id'];
        Search::updateProductById($wikiid);
    }


    public static function admAddTagsRelate($goodsId, $title)
    {
        $info = mGoodsExtendInfo::get(['tags_content'], ['goods_id' => $goodsId]);

        if (empty($info)) {
            return [];
        }

        $tagsList = explode(',', $info['tags_content']);

        if (!in_array($title, $tagsList)) {
            array_push($tagsList, $title);
        }

        mGoodsExtendInfo::update(['tags_content' => trim(implode(',', $tagsList), ',')], ['goods_id' => $goodsId]);

        cGoods::delGoods($goodsId);
        searchGoods::updateByGoodsId($goodsId);
    }

    public static function admGetTagsList($goodsId)
    {
        $info = mGoodsExtendInfo::get(['tags_content'], ['goods_id' => $goodsId]);

        if (empty($info['tags_content'])) {
            return [];
        }

        $tagsList = explode(',', $info['tags_content']);

        return $tagsList;
    }

    public static function admDelTag($goodsId, $title)
    {
        $info = mGoodsExtendInfo::get(['tags_content'], ['goods_id' => $goodsId]);

        if (empty($info['tags_content'])) {
            return [];
        }

        $tagsList = explode(',', $info['tags_content']);
        $tagsList = array_filter($tagsList, function ($v) use ($title) {
            if ($v != $title) {
                return true;
            }
            return false;
        });

        mGoodsExtendInfo::update(['tags_content' => trim(implode(',', $tagsList), ',')], ['goods_id' => $goodsId]);

        cGoods::delGoods($goodsId);
        searchGoods::updateByGoodsId($goodsId);
    }

    public static function admSetRate($goodsId, $ratio, $ratioExt)
    {
        mGoodsExtendInfo::update(['ratio' => $ratio, 'ratio_ext' => $ratioExt], ['goods_id' => $goodsId]);
        cGoods::delGoods($goodsId);
    }

    /**
     * 获取sku需要导出的数据
     * @param $goodsIds
     * @return array
     */
    private static function getSkuInfo($goodsIds)
    {
        $skuIds = [];
        $skuInfo = sSku::sku($goodsIds, sSku::FIELDS_GROUP_ALL);
        foreach ($skuInfo as $goods => $info) {
            foreach ($info['sku_info'] as $sku) {
                $skuIds[] = $sku['sku_id'];
            }
        }

        $addCartNum = self::getSkuAddCartNum($skuIds);

        $addCartPeopleNum = self::getSkuAddCartPeopleNum($skuIds);

        $skuSellNum = self::getSkuSellNum($skuIds);

        // 拼装信息
        $skuList = [];
        foreach ($goodsIds as $goodsId) {
            if (isset($skuInfo[$goodsId]['sku_info']) && $skuInfo[$goodsId]['sku_info']) {
                foreach ($skuInfo[$goodsId]['sku_info'] as $info) {
                    $skuList[$goodsId][] = [
                        'sku_id' => $info['sku_id'],
                        'sku_name' => $info['sku_desc'],
                        'price' => $info['ori_price'],
                        'sku_stock' => $info['stock'],
                        'sku_add_cart_num' => isset($addCartNum[$info['sku_id']]) ? $addCartNum[$info['sku_id']] : 0,
                        'sku_add_cart_people_num' => isset($addCartPeopleNum[$info['sku_id']]) ? $addCartPeopleNum[$info['sku_id']] : 0,
                        'sku_sell_num' => isset($skuSellNum[$info['sku_id']]) ? $skuSellNum[$info['sku_id']] : 0,
                    ];
                }
            }
        }
        return $skuList;
    }

    /**
     * 获取sku的加购数量
     * @param $skuIds
     * @return array
     */
    private static function getSkuAddCartNum($skuIds)
    {
        $addCartNum = [];
        $cartNum = mCart::admGetCartNumBySKUIds($skuIds);
        $cartVNum = mCartv::admGetCartNumBySKUIds($skuIds);
        foreach ($cartNum as $cart) {
            $addCartNum[$cart['sku_id']] = $cart['count'];
        }

        foreach ($cartVNum as $vCart) {
            if (isset($addCartNum[$vCart['sku_id']])) {
                $addCartNum[$vCart['sku_id']] = $vCart['count'] + $addCartNum[$vCart['sku_id']];
            } else {
                $addCartNum[$vCart['sku_id']] = $vCart['count'];
            }
        }

        return $addCartNum;
    }

    public static function updateLastCategory($goodsId, $data)
    {
        $categroy2 = $data['second_category_id'];
        $categroy3 = isset($data['category_3']) ? $data['category_3'] : 0;
        $categroy4 = isset($data['category_4']) ? $data['category_4'] : 0;
        $lastCategory = $categroy4 ?: $categroy3 ?: $categroy2;
        mGoodsBasicInfo::updateData([
            'third_category_id' => $categroy3,
            'four_category_id' => $categroy4,
            'last_category_id' => $lastCategory
        ], ['goods_id' => $goodsId]);
        sleep(2); //主从延迟
        searchGoods::updateByGoodsId($goodsId);
    }

    /**
     * 获取sku的加购人数
     * @param $skuIds
     * @return array
     */
    private static function getSkuAddCartPeopleNum($skuIds)
    {
        $addCartPeopleNum = [];
        $skuAddCartPeopleNum = mCart::admGetAddCartPeopleNumBySkuIds($skuIds);
        $skuAddCartVPeopleNum = mCartV::admGetAddCartPeopleNumBySkuIds($skuIds);
        foreach ($skuAddCartPeopleNum as $info) {
            if (isset($addCartPeopleNum[$info['sku_id']])) {
                $addCartPeopleNum[$info['sku_id']] = $addCartPeopleNum[$info['sku_id']] + $info['count'];
            } else {
                $addCartPeopleNum[$info['sku_id']] = $info['count'];
            }
        }


        foreach ($skuAddCartVPeopleNum as $info) {
            if (isset($addCartPeopleNum[$info['sku_id']])) {
                $addCartPeopleNum[$info['sku_id']] = $addCartPeopleNum[$info['sku_id']] + $info['count'];
            } else {
                $addCartPeopleNum[$info['sku_id']] = $info['count'];
            }
        }
        return $addCartPeopleNum;
    }

    /**
     * 获取sku销售数量
     * @param $skuIds
     * @return array
     */
    private static function getSkuSellNum($skuIds)
    {
        $skuSellTotal = [];
        $sellTotal = mOrderGoods::admGetCartNumBySkuIds($skuIds);
        foreach ($sellTotal as $total) {
            $skuSellTotal[$total['sku_id']] = $total['count'];
        }
        return $skuSellTotal;
    }

}